package com.imooc.service.Impl;

import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.UsersBo;
import com.imooc.service.UserService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.MD5Utils;
import com.imooc.utils.enums.Sex;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @Author: hhh
 * @CreateTime: 2025-05-18
 * @Description: 用户表实现类
 * @Version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UsersMapper  usersMapper;

    @Autowired
    private Sid sid;

    public static  final String DEFAULT_USER_FACE = "https://c-ssl.dtstatic.com/uploads/item/201906/22/20190622223910_vqmho.thumb.1000_0.jpeg";

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameExist(String username) {
        Example userExample = new Example(Users.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        // 查询条件
        userCriteria.andEqualTo("username", username);

        Users users = usersMapper.selectOneByExample(userExample);
        return users != null;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UsersBo usersBo) {
        String userId = sid.nextShort();
        Users user = new Users();
        user.setId(userId);
        user.setUsername(usersBo.getUsername());
        try {
            user.setPassword(MD5Utils.getMD5Str(usersBo.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 默认用户昵称同用户名
        user.setNickname(usersBo.getUsername());
        // 默认头像
        user.setFace(DEFAULT_USER_FACE);
        // 默认生日
        user.setBirthday(DateUtil.stringToDate("2025-05-18"));
        // 默认性别
        user.setSex(Sex.secret.type);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        usersMapper.insert(user);
        return user;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String password) {
        Example userExample = new Example(Users.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        // 查询条件
        userCriteria.andEqualTo("username", username);
        userCriteria.andEqualTo("password", password);
        return usersMapper.selectOneByExample(userExample);
    }
}
